package com.tqz.web.flux.demo.route;

import com.tqz.web.flux.demo.function.UserHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

import java.util.Optional;

/**
 * <p> {@link RouterFunction} 相当于 {@link RequestMapping} ，将请求的url映射到具体的handler中。
 *
 * @author tianqingzhao
 * @since 2023/3/4 20:50
 */
@Configuration
public class UserRoute {

    @Bean
    public RouterFunction<ServerResponse> getUserRouteFunction(UserHandler userHandler) {
        return RouterFunctions.route()
                .filter((request, next) -> {
                    Optional<String> token = request.queryParam("token");
                    if (!token.isPresent()) {
                        return ServerResponse.status(HttpStatus.UNAUTHORIZED).build();
                    }
                    return next.handle(request);
                })
                .GET("/function/getUser", userHandler::getUser)
                .build();
    }
}
